package com.zzty.zzlp.controller;


import com.zzty.zzlp.commom.FileUpload;
import com.zzty.zzlp.entity.User;
import com.zzty.zzlp.service.SelfExamService;
import com.zzty.zzlp.service.SelfExamTransationService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/SelfExamTransation")
public class SelfExamTransationController {

    @Autowired
    SelfExamService ses;

    @Autowired
    SelfExamTransationService sets;

    @RequestMapping(value = "/toSelfExam")
    public String toSelfExam() {
        return "SelfExam";
    }

    @RequestMapping(value = "/judge", produces = {"text/html;charset=UTF-8;"})
    @ResponseBody
    public String judge(HttpSession httpSession) {
        System.out.println("judge");
        User user = (User) httpSession.getAttribute("User");
//        User user = new User();
//        user.setId(63);

        String result = "";
        Integer examId = ses.searchExamId(user.getId());
        System.out.println("examId:" + examId);
        JSONObject jsonObj = new JSONObject();
        String clazzName = ses.searchClazzByUserId(user.getId());
        if (!judgeQstExist(user.getId())) {
            System.out.println("No Qst");
            result = "无法开始竞赛";
            return result;
        } else {
            if (!isTimeToStart()) {
                System.out.println("Time Mistake");
                result = "无法开始竞赛";
                return result;
            } else {

                String startTime = sets.searchStartTime(examId, user.getId());
                String time = startTime.split(" ")[1];
                System.out.println(time);
                String countdown = countdown(time);
                jsonObj.put("countdown", countdown);
                System.out.println(countdown);
                ArrayList qstContent = null;
                String s = "";
                qstContent = showQst(Integer.valueOf(clazzName));
                for (int i = 0; i < qstContent.size(); i++) {
                    s += (i + 1) + "." + qstContent.get(i);
                }
                jsonObj.put("qstContent", s);
                System.out.println(jsonObj.toString());
                return jsonObj.toString();
            }
        }
    }

    @RequestMapping(value = "/updateTotalTime", produces = {"text/html;charset=UTF-8;", "application/json;"})
    @ResponseBody
    public String updateTotalTime(HttpSession httpSession) {
        User user = (User) httpSession.getAttribute("user");

        int examId = ses.searchExamId(user.getId());
        int totalTime = sets.searchTotalTime(examId, user.getId());
        // System.out.println(totalTime);
        if (sets.getIsTotalTimeExist()) {

            return "请勿重复提交";
        }
        return "";

    }

    @RequestMapping(value = "/submit", produces = {"text/html;charset=UTF-8;", "application/json;"})
    public void submit(@RequestParam(value = "selffileName", required = false) MultipartFile file,
                       HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User) request.getSession().getAttribute("User");
//        User user = new User();
//        user.setId(63);
//        String name = user.getName();
        Integer examId = ses.searchExamId(user.getId());

        Integer userId = user.getId();

        if (sets.searchTotalTime(examId, userId) == null) {
            try {
                upLoad(file, examId, userId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            response.sendRedirect("..//html/main.html#!/zzty");
        } else {
            response.sendRedirect("../html/main.html#!/zzty");
        }
    }

    public boolean judgeQstExist(int userid) {
        if (ses.judgeQstExist(userid)) {
            return true;
        }
        return false;
    }

    // 是否到答题时间
    protected boolean isTimeToStart() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("HH");
        int hour = Integer.parseInt(sdf.format(date));
        if (hour >= 10 && hour <= 23) {
            return true;
        } else {
            return false;
        }
    }

    // 计算剩余时间
    protected String countdown(String startTime) {
//        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String stimes[] = startTime.split(":");
        int shour = Integer.parseInt(stimes[0]);
        int smin = Integer.parseInt(stimes[1]);
        int ssecond = Integer.parseInt(stimes[2]);
        int sseconds = shour * 60 * 60 + smin * 60 + ssecond;
        int finalseconds = sseconds + 2 * 60 * 60;
        String nowTime = getSysTime();
        String ntimes[] = nowTime.split(":");
        int nhour = Integer.parseInt(ntimes[0]);
        int nmin = Integer.parseInt(ntimes[1]);
        int nsecond = Integer.parseInt(ntimes[2]);
        int nseconds = nhour * 60 * 60 + nmin * 60 + nsecond;
        int leftTime = finalseconds - nseconds;

        return leftTime + "";
    }

    public String getSysTime() {
        Calendar now = Calendar.getInstance();
        String systime = now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":"
                + now.get(Calendar.SECOND);
        return systime;
    }

    // 显示题目内容
    public ArrayList showQst(int cName) {
        try {
            return ses.searchQstContent(ses.searchQstId(cName));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void upLoad(MultipartFile file, Integer examId, Integer userId) throws Exception {
        System.out.println("upload");
        try {
            Map<String, String> fileInfo = FileUpload.uploadFile(file, "selfExam");
            String answers = fileInfo.get("filename");
            System.out.println("-------------" + answers);
            sets.updateAnswers(examId, userId, answers);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/submit1", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject submit1(@RequestParam(value = "files") MultipartFile files, HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("User");
//        User user = new User();
//        user.setId(63);
//        String name = user.getName();
        Integer examId = ses.searchExamId(user.getId());

        Integer userId = user.getId();
        JSONObject jb = new JSONObject();
        if (sets.searchTotalTime(examId, userId) == null) {
            System.out.println("totalTime:null");
            upLoad(files, examId, userId);
            jb.put("massage", "success");
            return jb;
        } else {
            jb.put("massage", "fail");
            return jb;
        }
    }

}
